<template>
  <div class="page-container">
    <el-card class="repair-form">
      <template #header>
        <div class="form-header">
          <h2>🔧🔧 设备报修</h2>
          <el-button type="primary" @click="submitRepair" size="small">
            <i class="el-icon-upload"></i> 提交报修
          </el-button>
        </div>
      </template>
      
      <el-form :model="repairForm" :rules="rules" ref="repairFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="场馆名称" prop="venueId">
              <el-select 
                v-model="repairForm.venueId" 
                placeholder="请选择场馆"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="venue in venueList"
                  :key="venue.id"
                  :label="venue.venueName"
                  :value="venue.id"
                >
                  <span style="float: left">{{ venue.venueName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ venue.status }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="16">
            <el-form-item label="损坏详情" prop="damageDetails">
              <el-input
                v-model="repairForm.damageDetails"
                type="textarea"
                placeholder="请输入设备损坏详情（如损坏部位、严重程度等）"
                :autosize="{ minRows: 3, maxRows: 6 }"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="repair-history">
      <template #header>
        <h2>📋📋 我的报修记录</h2>
      </template>
      
      <el-table 
        :data="repairHistory" 
        stripe
        border
        style="width: 100%"
        :default-sort="{prop: 'reportTime', order: 'descending'}"
        align="center"
      >
        <el-table-column 
          prop="venueName" 
          label="场馆名称" 
          sortable
          width="220"
        ></el-table-column>
        
        <el-table-column 
          prop="damageDetails" 
          label="损坏详情"
          min-width="300"
        >
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.damageDetails" placement="top">
              <div class="damage-details">
                {{ truncateText(scope.row.damageDetails, 50) }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="reportTime" 
          label="报修时间" 
          sortable
          width="180"
        >
          <template #default="scope">
            {{ formatDate(scope.row.reportTime) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="status" 
          label="报修状态" 
          sortable
          width="120"
        >
          <template #default="scope">
            <el-tag
              :type="getTagType(scope.row.status)"
              size="medium"
              effect="dark"
              round
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="操作" 
          width="150"
        >
          <template #default="scope">
            <el-button 
              type="primary" 
              icon="Edit" 
              circle
              @click="editRepair(scope.row)"
            />
            <el-button 
              type="danger" 
              icon="Delete" 
              circle
              @click="deleteRepair(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>

  <el-dialog v-model="editDialogVisible" title="修改报修信息" width="40%">
    <el-form :model="editForm" :rules="editRules" ref="editFormRef">
      <el-form-item label="场馆名称" prop="venueId">
        <el-select v-model="editForm.venueId" placeholder="请选择场馆" style="width: 100%">
          <el-option
            v-for="venue in venueList"
            :key="venue.id"
            :label="venue.venueName"
            :value="venue.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="损坏详情" prop="damageDetails">
        <el-input
          v-model="editForm.damageDetails"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 6 }"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmEdit">确认修改</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.page-container {
  padding: 24px;
  background: #f5f7fa;
}

.repair-form {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.repair-history {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.el-table {
  margin-top: 16px;
}

.el-tag {
  font-weight: 500;
  letter-spacing: 0.5px;
}

.damage-details {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

// 报修表单数据
const repairForm = ref({
  venueId: null,
  damageDetails: '',
})

// 场馆列表
const venueList = ref([])
// 报修记录
const repairHistory = ref([])

// 表单验证规则
const rules = {
  venueId: [
    { required: true, message: '请选择场馆', trigger: 'change' }
  ],
  damageDetails: [
    { required: true, message: '请输入损坏详情', trigger: 'blur' },
    { min: 5, message: '损坏详情至少5个字符', trigger: 'blur' }
  ]
}

// 编辑表单验证规则
const editRules = {
  venueId: [
    { required: true, message: '请选择场馆', trigger: 'change' }
  ],
  damageDetails: [
    { required: true, message: '请输入损坏详情', trigger: 'blur' },
    { min: 5, message: '损坏详情至少5个字符', trigger: 'blur' }
  ]
}

const repairFormRef = ref(null)
const editFormRef = ref(null)

// 场馆映射 - 用于通过ID获取场馆名称
const venueMap = ref({})

// 获取场馆列表
const getVenueList = async () => {
  try {
    const response = await request.get('/getVenueInfo')
    venueList.value = response.data.data
    
    // 创建场馆ID到名称的映射
    venueMap.value = {}
    venueList.value.forEach(venue => {
      venueMap.value[venue.id] = venue.venueName
    })
  } catch (error) {
    console.error('获取场馆列表失败', error)
    ElMessage.error('获取场馆列表失败')
  }
}

// 获取报修记录
const getRepairHistory = async () => {
  try {
    const response = await request.get('/getRepairHistory')
    const repairs = response.data.data || []
    
    // 添加场馆名称到报修记录
    repairHistory.value = repairs.map(repair => {
      return {
        ...repair,
        venueName: venueMap.value[repair.venueId] || '未知场馆'
      }
    })
  } catch (error) {
    console.error('获取报修记录失败', error)
    ElMessage.error('获取报修记录失败')
  }
}

// 提交报修
const submitRepair = async () => {
  if (!repairFormRef.value) return
  try {
    await repairFormRef.value.validate()
    
    const submitData = {
      venueId: repairForm.value.venueId,
      damageDetails: repairForm.value.damageDetails
    }
    
    const response = await request.post('/submitRepair', submitData)
    
    if (response.data.code === 200) {
      ElMessage.success('报修提交成功')
      repairHistory.value = [] // 清空缓存
      await getRepairHistory()
      repairFormRef.value.resetFields()
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    if (error?.response?.data) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('提交失败：' + error.message)
    }
  }
}

const editDialogVisible = ref(false)
const editForm = ref({ venueId: null, damageDetails: '' })
const currentEditId = ref(null)
const currentEditstatus = ref(null)
const currentEditreport_time = ref(null)
// 修改报修信息
const editRepair = (row) => {
  editForm.value = { 
    venueId: row.venueId,
    damageDetails: row.damageDetails
  }
  currentEditId.value = row.id
  currentEditstatus.value=row.status
  currentEditreport_time.value=row.report_time
  editDialogVisible.value = true
}

const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()
    
    const submitData = {
      venueId: editForm.value.venueId,
      damageDetails: editForm.value.damageDetails,
      id: currentEditId.value,
      status: currentEditstatus.value,
      report_time: currentEditreport_time.value
    }
    
    const response = await request.put(`/updateRepair/${currentEditId.value}`, submitData)
    
    if (response.data.code === 200) {
      ElMessage.success('修改成功')
      repairHistory.value = [] // 清空缓存
      await getRepairHistory()
      editDialogVisible.value = false
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    if (error?.response?.data) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('修改失败：' + error.message)
    }
  }
}

// 删除报修记录
const deleteRepair = async (row) => {
  try {
    const response = await request.delete(`/deleteRepair/${row.id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      await getRepairHistory()
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('删除失败：' + (error.response?.data?.msg || '服务器错误'))
  }
}

// 根据状态获取 tag 类型
const getTagType = (status) => {
  const statusMap = {
    '未维修': 'warning',
    '维护中': 'primary',
    '已维修': 'success'
  }
  return statusMap[status] || ''
}

// 文本截断方法
const truncateText = (text, maxLength) => {
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString()
}


onMounted(async () => {
  // 先获取场馆列表
  const venueListLoaded = await getVenueList()
  
  if (venueListLoaded) {
    // 然后获取报修信息
    await getRepairHistory()
  } else {
    // 如果场馆列表加载失败，尝试直接加载报修信息
    console.warn('场馆列表加载失败，尝试直接加载报修信息')
    await getRepairHistory()
  }
})
</script>